package com.njit.postbar;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.njit.postbar.model.Circle;
import com.njit.postbar.model.UpLoadBean;
import com.njit.postbar.model.User;
import com.njit.postbar.server.MyServer;
import com.njit.postbar.utils.Remove;
import com.njit.postbar.utils.UploadImage;

import org.litepal.LitePal;

import java.io.File;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
 *@author yuruiqiao
 *@date 2020/6/9
 *@description 两用,一个是创建圈子,另一个是修改圈子
 */
public class CreateCircle extends UploadImage {

    private User user;
    private EditText title;
    private EditText synopsis;
    private Button create,uploadBtn,update;
    private ImageView preImage;
    private String url = "";
    private Circle existed;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.circle_create);
        Remove.removeTop(this);
        Intent intent = this.getIntent();
        user = (User) intent.getSerializableExtra("user");
        existed = (Circle) intent.getSerializableExtra("circle");
        title = findViewById(R.id.circle_title);
        synopsis = findViewById(R.id.synopsis);
        uploadBtn = findViewById(R.id.upload_image);
        update = findViewById(R.id.update);
        create = findViewById(R.id.create);
        preImage = findViewById(R.id.preview_image);
        //设置监听器
        setListeners();

        if(existed!=null){
            url = existed.getPreviewImageUrl();
            title.setText(existed.getTitle());
            synopsis.setText(existed.getSynopsis());
            Glide.with(this).load(existed.getPreviewImageUrl()).into(preImage);
            preImage.setVisibility(View.VISIBLE);
            update.setVisibility(View.VISIBLE);
            create.setVisibility(View.INVISIBLE);
        }else{
            preImage.setVisibility(View.INVISIBLE);
            update.setVisibility(View.INVISIBLE);
            create.setVisibility(View.VISIBLE);
        }
    }

    /**
     *@author yuruiqiao
     *@date 2020/6/5
     *@description 必须重写方法不然会出现线程错误
     */
    @Override
    protected void updateFile(File file) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MyServer.Url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        MyServer myServer = retrofit.create(MyServer.class);
        //文件封装
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"),file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                "file", file.getName(), requestBody);
        //文本封装
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"),"img");
        final Observable<UpLoadBean> upload = myServer.upload(requestBody1,filePart);
        upload.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpLoadBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {}
                    @Override
                    public void onNext(UpLoadBean upLoadBean) {
                        if (upLoadBean != null && upLoadBean.getCode() == 200) {
                            //这边获得图片的地址
                            url = upLoadBean.getData().getUrl();
                            //更新图像
                            Glide.with(CreateCircle.this).load(upLoadBean.getData().getUrl()).into(preImage);
                            preImage.setVisibility(View.VISIBLE);
                            //下面是提示信息
                            Log.d("lzj", upLoadBean.getData().getUrl());
                            showDialog("上传成功,地址为:"+url,null);
                        } else {
                            Log.d("lzj", "failed");
                            showDialog("上传失败😅",null);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {}
                    @Override
                    public void onComplete() {}
                });
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 提示框
     */
    private void showDialog(String message,DialogInterface.OnClickListener listener){
        AlertDialog.Builder builder  = new AlertDialog.Builder(CreateCircle.this);
        builder.setTitle("提示") ;
        builder.setMessage(message) ;
        builder.setPositiveButton("是",listener);
        builder.show();
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/7
     *@description 检查填写信息是否准确
     */
    private boolean checkInfo(){
        if(title.getText().toString().equals("")){
            showDialog("圈子没有名字怎么行😒",null);
            return false;
        }
        if(synopsis.getText().toString().equals("")){
            showDialog("给自己的圈子写点简介哦😜",null);
            return false;
        }
        if(synopsis.getText().toString().length()>50){
            showDialog("简介不超过50个字哦😜",null);
            return false;
        }
        List<Circle> circles = LitePal.where("title=?",title.getText().toString()).find(Circle.class);
        if(circles.size()>0 && existed==null){
            showDialog("该名字已经被人抢走啦😅",null);
            return false;
        }
        return true;
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/7
     *@description 监听器
     */
    public void setListeners(){
        //检查名字
        title.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                    List<Circle> circles = LitePal.where("title=?",title.getText().toString()).find(Circle.class);
                    if(circles.size()>0 && existed==null){
                        showDialog("该名字已经被人抢走啦😅",null);
                        title.setText("");
                    }
                }
            }
        });
        //上传头像
        uploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CreateCircle.this.takesD();
            }
        });

        //创建按钮
        create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(checkInfo()) {
                    Circle circle = new Circle();
                    circle.setCreateTime(new Date());
                    circle.setTitle(title.getText().toString());
                    circle.setSynopsis(synopsis.getText().toString());
                    circle.setLikeNumber(0);
                    circle.setPreviewImageUrl(url);
                    circle.setUserId(user.getId());
                    circle.save();
                    showDialog("圈子成功创建😄", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                }
            }
        });

        //修改按钮
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(existed != null && checkInfo()) {
                    Circle circle = LitePal.find(Circle.class,existed.getId());
                    circle.setUpdateTime(new Date());
                    circle.setTitle(title.getText().toString());
                    circle.setSynopsis(synopsis.getText().toString());
                    circle.setPreviewImageUrl(url);
                    circle.save();
                    showDialog("圈子成功修改😄", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                }
            }
        });
    }
}
